//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;

namespace OpenLS.Spreadsheet.Expressions
{
    class BoundingRangeExpression: BinaryRangeExpression
    {
        public BoundingRangeExpression(Expression left, Expression right)
            : base(left, right)
        {
        }

        internal CellEnumeratorExpression Simplified
        {
            get
            {
                if (Left is CellReferenceExpression && Right is CellReferenceExpression)
                {
                    var l = (CellReferenceExpression) Left;
                    var r = (CellReferenceExpression) Right;
                    return new RangeReferenceExpression(l.CellReference, r.CellReference, l.Caller);
                }
                return this;
            }
        }
        internal override Expression Transposed(Cell target)
        {
            return new BoundingRangeExpression(Left.Transposed(target), Right.Transposed(target));
        }


        public override string GetText(TextContext context)
        {
            return Left.GetText(context) + ":" + Right.GetText(context);
        }

        protected override ICellEnumerator CreateCellsValue(ICellEnumerator enumerator, ICellEnumerator cellEnumerator)
        {
            Worksheet lw = Worksheet;
            if (lw == null)
                return new CellError(Errors.RefError);
            var leftRange = enumerator.ToRange();
            var rightRange = cellEnumerator.ToRange();
            var topLeft = new CellAddress(
                Math.Min(leftRange.RowIndex, rightRange.RowIndex),
                Math.Min(leftRange.ColumnIndex, rightRange.ColumnIndex)
                );
            var bottomRight = new CellAddress(
                Math.Max(leftRange.RowIndex + leftRange.RowSpan - 1, rightRange.RowIndex + rightRange.RowSpan - 1),
                Math.Max(leftRange.ColumnIndex + leftRange.ColumnSpan - 1, rightRange.ColumnIndex + +rightRange.ColumnSpan - 1)
                );
            var ra = new RangeAddress(topLeft, bottomRight);
 
            return CellsRange.Create(Worksheet, ra);
        }
        protected override Expression CreateExpression(CellEnumeratorExpression left, CellEnumeratorExpression right)
        {
            return new BoundingRangeExpression(left, right);
        }
    }
}